#include "Sprites.h"
#include "GameDeviceSingleton.h"


Sprites::Sprites(Rect* rect)
{
	// init default data
	this->rect = NULL;
	this->container = NULL;
	this->currentSprite = NULL;
	this->spriteHandler = NULL;
	this->matrix = NULL;

	this->initSprites();
	this->initState();
	this->initRect(rect);

	this->spriteHandler = *(GameDeviceSingleton::getInstance()->getSpriteHandler());
}

void Sprites::initSprites() {
	this->container = new std::map<int, Sprite*>();
}

void Sprites::initState() {
	this->state = SPR_STATE_DEF;
}

void Sprites::initRect(Rect* rect) {
	this->rect = rect;
}

void Sprites::draw(int alpha) {
	if (state == 0) return; 
	// demo draw sprite without matrix flip
	this->currentSprite->Render(NULL, rect->X, rect->Y, alpha);
	//check null
	if (this->currentSprite == NULL || 
		rect == NULL || 
		this->matrix == NULL)
		return;
	//draw current
	this->currentSprite->Render(*(GameDeviceSingleton::getInstance()->getBackground()), rect->X, rect->Y, alpha);
}

void Sprites::draw() {
	draw(255);
}

void Sprites::addSprite(int state, int spriteId, int framerate) {
	//create sprite
	//check spritehandler is null
	if (spriteHandler != NULL) {
		Sprite* sprite = new Sprite(spriteHandler, spriteId, true);
		sprite->setDelay(framerate);
		//insert to container
		container->insert(std::make_pair(state, sprite));
	}
}

void Sprites::addSprite(int state, int spriteId) {
	//create sprite
	//check spritehandler is null
	if (spriteHandler != NULL) {
		Sprite* sprite = new Sprite(spriteHandler, spriteId, true);
		//insert to container
		container->insert(std::make_pair(state, sprite));
	}
}

bool Sprites::checkState(int state) {
	return !(currentSprite == NULL || this->state != state);
}

Sprite* Sprites::getSprite(int state) {
	//find in container
	std::map<int, Sprite*>::iterator it =  container->find(state);
	//check null
	if (it == container->end()) {
		return NULL;
	} 
	//return res
	return it->second;
}

void Sprites::setState(int state) {
	//get sprite by state input
	Sprite* sprite = this->getSprite(state);
	//check null
	if (sprite != NULL && sprite != this->currentSprite && state != this->state) {
		this->currentSprite = sprite;
		this->currentSprite->Reset();
		this->state = state;
	}
}

void Sprites::setCurrentToEnd() {
	currentSprite->setToEnd();
}

void Sprites::setCurrentToStart() {
	currentSprite->setToStart();
}

void Sprites::updateCurrent() {
	if (state == 0) return;
	//check current not null
	if (currentSprite != NULL) {
		currentSprite->Next();
	}
}

void Sprites::initSpriteHandler(LPD3DXSPRITE spriteHandler) {
	//this->spriteHandler = spriteHandler;
}

void Sprites::initMatrix(D3DXMATRIX *matrix) {
	this->matrix = matrix;
}

Sprites::~Sprites() {
	std::map<int, Sprite*>::iterator it = container->begin();
	for (; it != container->end(); it++) {
		delete it->second;
	}
	delete container;
}